console.log('tax injected');
import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';

let baseInfoCache;
$(document).ready(function () {
  if (/\/v2\/login_v2_init.jsp/g.test(window.location.pathname)) {
    window.postMessage({
      event: 'getBaseInfo'
    }, '*');
  }
});

window.addEventListener('message', async function ({ data }) {
  // 只监听来自于content script的信息
  if (data.sender !== 'content-script') {
    return false;
  }
  if (data.event === 'setSaasData') {
    fillInput(await transformDataByOpenWeb(data.data));
  }
  if (data.event === 'getNationData') {
    getNationData();
  }

  if (data.event === 'getBaseInfo') {
    console.log(11111)
    baseInfoCache = data.data;
    await autoInputAccount(baseInfoCache);
  }
}, false);
async function waitTimeOut(timeout = 1000) {
  return new Promise(function (resolve, reject) {
    setTimeout(() => {
      resolve();
    }, timeout);
  });
}

async function autoInputAccount({ companyInfo }) {
  debugger
  $('.header-login').click();
  await waitTimeOut(500);
  if ($('#Bullayer')) {
    $('#Bullayer').hide();
  }
  await waitTimeOut(500);
  $('.login-choice-shui').click();
  await waitTimeOut(500);
  const iframeEle = document.querySelector(
    'iframe[src="/etax/jsp/v2/login_bs.jsp"]'
  );
  let iframe = null;
  if (iframeEle) {
    iframe = iframeEle.contentWindow.document;
  }
  if (iframe) {
    // if (iframe.getElementsByClassName('login-phone')[0]) {
    //   iframe.getElementsByClassName('.')[0].click();
    //   await waitTimeOut(500);
    // }
    iframe.querySelector('.login-control > a:nth-child(3)').click();
    await waitTimeOut(500);

    companyInfo = companyInfo || {};
    iframe.querySelectorAll('#userName')[1].value =
      companyInfo.nationalTaxAccount || companyInfo.nationalTaxId;
    iframe.querySelectorAll('#passwdNsr')[1].value =
      companyInfo.nationalTaxPass;
  }
}

/**
 * 调用接口获取公司信息
 */
function getNationData() {
  let taxInfo = {
    institution: '2013', // 国税对应制度 2007 | 2013
    nsrsbh: baseInfoCache.companyInfo.nationalTaxId, // 纳税人申报号
    nsrmc: baseInfoCache.companyInfo.companyName, // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: '', // 税款所属期止
    outPutType: 'xml' // 填报方式
  };
  window.postMessage({
    event: 'backNationData',
    data: {
      taxInfo: taxInfo
    }
  }, '*');
}

function fillInput({ saasData, baseInfo }) {
  let message = '';
  if (saasData.data.type === 'file') {
    message = downloadFile(saasData.data.data, baseInfo);
  } else {
    message = '不支持json方式，下载文件失败！';
  }

  window.postMessage({
    event: 'fillInputDone',
    data: {
      message: message || '下载文件成功'
    }
  }, '*');
}

/**
 * 下载文件
 * @param blob
 */
function downloadFile(blob, { taxInfo }) {
  blob = new Blob([blob], { type: 'text/xml' });
  let a = document.createElement('a');
  // 指定生成的文件名
  let name = `${taxInfo.nsrsbh}_${taxInfo.institution === '2013' ? 'ZL019' : 'ZL001'}`;
  const start = taxInfo.skssqq.replace(/-/g, '');
  const end = taxInfo.skssqz.replace(/-/g, '');
  a.download = `${name}_${start}_${end}.xml`;
  a.href = URL.createObjectURL(blob);
  document.body.appendChild(a);
  a.click();
}
